/**
 * @description
 *
 * @pargram
 *          title (string): 模块标题 （默认字符串 '附件'）
 *          actionUrl (string): 文件上传Url （默认字符串 ''）
 *          subTitle (string): 模块副标题标题 （默认字符串 '文件只支持PDF格式'
 *          showUploadButton (Boolean): 是否展示上传文件按钮 （默认true）

 *          showCustomButton (Boolean): 是否展示自定义按钮 （默认false）
 *          customButtonText (Boolean): 自定义按钮名称 （默认''）

 *          maxNumber (Number): 最大上传文件数量 （默认1）
 *          maxSize (Number): 单个文件最大上传大小 （默认 单位Mb）
 *          fileTypes (Array): 可以上传文件类型 （默认PDF）
 *          showDleteButton (Boolean): 是否展示s删除按钮 （默认false）
 *          fileData (Array): 文件数据（默认为[]）
 *          botttomExternalShow: 文件展示外部底部展示
 *          botttomExternalRender:文件展示外部底部展示render
 *          
 * @return
 *          @uploadsuccess 上传文件返回emit事件 返回参数 {name: res.data.fileName, size: file.size, url: res.data.url}
 *          @deleteFile 文件删除返回emit 事件 返回参数(item,index) (附件列表Item 以及索引)
 *          @customevent 自定义按钮的返回事件
 * @auth yxj
 */
<template>
    <div class="uploadComponent">
        <div class="title">
            <div class = "titleTip"></div>
            <div class = "titleContent" v-text = "title"></div>
            <div class = "subTitle" v-text = "subTitle"></div>
            <el-button size="mini" type = "text" class = "titleButton" v-if = "showUploadButton" :disabled = "fileData.length >= maxNumber" @click = "chooseFile">上传文件</el-button>
            <el-upload
                ref="uploadComponentRef"
                action
                style = "display: none;"
                class="upload-demo"
                multiple
                :limit= maxNumber
                :auto-upload = "false"
                :on-exceed="handleExceed"
                :on-change = "beforeUpload"
                :file-list="fileData">
                <el-button size="small" ref = "upLoadButton" type="primary">点击上传</el-button>
            </el-upload>
            <el-button size="mini" style = "margin-left: 20px; width: 100px;height:30px;" type = "text" class = "titleButton" v-if = "showCustomButton" @click = "$emit('customevent')"><span v-text = "customButtonText"></span></el-button>
        </div>
        <div class = "content" v-html = "contentHtml" v-if = "contentHtml"></div>
        <div class = "fileShow">
            <div class = "fileItem" v-for="(item, index) in fileData" :key= index>
                <div class="fileItemMain">
                    <!-- 图片 -->
                    <div style = "height: 50px;">
                        <img src="../../../../assets/image/pdf.png" style = "width: 50px;" />
                    </div>
                    <!-- 右边展示 -->
                    <div class="fileInfo">
                        <div class = "fileTitle">
                            <span v-text="item.name" :title ="item.name"></span>
                        </div>
                        <div class = "fileAction">
                            <div class = "fileSize">
                                <span v-text="(Number(item.size)/1024).toFixed(2) >= 1024 ? (Number(item.size)/1024/1024).toFixed(2) + 'M': (Number(item.size)/1024).toFixed(2) + 'K'"></span>
                            </div>
                            <div class = "fileButtons">
                                <el-button size="mini" type = "text" class = "fileButton" @click="preview(item)"><span style="display:flex; align-items:center;"><img src="../../../../assets/image/preview.png" alt=""><span>预览</span></span></el-button>
                                <el-button size="mini" type = "text" class = "fileButton"><span style="display:flex; align-items:center;"><img src="../../../../assets/image/download.png" alt=""><span>下载</span></span></el-button>
                            </div>
                        </div>
                    </div>
                    <div class = "deleteButton" v-if="showDleteButton">
                        <i class="el-icon-close deleteButtonEl" @click = "deleteFile(item, index)"></i>
                    </div>
                </div>
                <template v-if = "botttomExternalShow">
                    <ex-slot v-if = "botttomExternalRender" :render = "botttomExternalRender" :row = "item" :index="index"/>
                </template>
            </div>
        </div>
    </div>
</template>
<script>
// 自定义内容的组件
let exSlot = {
    functional: true,
    props: {
    row: Object,
    render: Function,
    index: Number,
    column: {
        type: Object,
        default: null
    }
    },
    render: (h, data) => {
        const params = {
            row: data.props.row,
            index: data.props.index
        }
        if (data.props.column) params.column = data.props.column
        return data.props.render(h, params)
    }
}
export default {
    components : {
        exSlot
    },
    data () {
        return {
            files:[],
            fileStream:''
        }
    },
    props: {
        title: {
            type: String,
            default : '附件'
        },
        actionUrl:{
            type: Function,
            default : () => {
                return () => {}
            }
        },
        subTitle: {
            type: String,
            default : '文件只支持PDF格式'
        },
        showUploadButton: {
            type: Boolean,
            default: false
        },
        showCustomButton: {
            type: Boolean,
            default: false
        },
        customButtonText: {
            type: String,
            default : '附件'
        },
        maxNumber: {
            type: Number,
            default: 8
        },
        maxSize: {
            type: Number,
            default: 1 
        },
        fileTypes: {
            type:Array,
            default: () => {
                return ['PDF']
            }
        },
        showDleteButton: {
            type: Boolean,
            default: false
        },
        fileData: {
            type: Array,
            default : () => {
                return []
            }
        },
        botttomExternalShow : {
            type: Boolean,
            default: false
        },
        botttomExternalRender : {
            type: Function,
            default : () => {
                return () => {}
            }
        },
        contentHtml:{
            type: String,
            default : ''
        }
    },
    methods: {
        // 选择上传文件
        chooseFile() {
            this.$refs.upLoadButton.$el.click()
        },
        // beforeUpload 文件上传之前钩子函数 判断文件大小以及文件类型
        beforeUpload (file, fileList) {
            let sizeMb = (Number(file.size)/1024/1024).toFixed(2)
            let type = file.name.substr((file.name.lastIndexOf('.')+1))
            let correctSize = sizeMb < this.maxSize
            let correctType = this.fileTypes.find(item => {return item.toLowerCase() === type.toLowerCase()})
            if (!correctSize) {
                this.$message.warning(`当前限制上传文件 ${file.name}, 原因: 大小超过 ${this.maxSize} Mb`);
            }
            if (!correctType) {
                this.$message.warning(`当前限制上传文件 ${file.name}, 原因: 文件类型错误`);
            }
            if (!correctSize || !correctType) {
                this.$refs['uploadComponentRef'].clearFiles()
                return false
            }
            this.uploadFile(file)
        },
        // 文件上传
        uploadFile (file) {
            let _that = this
            let data = new FormData()
            data.append('multipartFile', file.raw)
            this.Api.uploadFile(data).then((res) => {
                if (res.code === '0') {
                    _that.$emit('uploadsuccess', {name: res.data.fileName, size: file.size, url: res.data.url})
                }
            })
        },
        // 文件上传成功
        upLoadSuccess(response, file, fileList) {
            console.log(response)
            console.log(file)
            console.log(fileList)
        },
        // 文件上传失败
        handleOnError (err, file, fileList) {
            
        },
        // 文件超出上传个数限制
        handleExceed(files, fileList) {
            console.log(fileList)
            console.log(files)
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        // 删除文件
        deleteFile (item, index) {
            this.$emit('deletefile', item, index)
        },
        // 预览文件
        preview(data) {
            let URL = this.$store.state.PortalManagement.fileIp + data.url
            window.open(URL, '_blank')
        }
        
    }
}
</script>
<style lang="less" scoped>
    .uploadComponent {
        background: #fff;
        .title {
            display: flex;
            padding: 20px;
            align-items: center;
            .titleTip {
                width: 4px;
                height: 14px;
                background: #3D7fff;
                margin-right: 10px;
            }
            .titleContent {
                font-weight: 600;
                color: #333333;
                font-size: 16px;
                line-height: 16px;
            }
            .subTitle {
                font-size: 12px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: rgba(153, 153, 153, 1);
                line-height: 17px;
                margin-left: 12px;
                flex: 1;
            }
            .titleButton {
                border: 1px solid #3D7FFF;
                color: #3D7FFF;
                width: 70px;
                height: 30px;
                font-weight: 500;
                border-radius: 4px;
            }
            .titleButton:hover {
                color: #66b1ff;
                border-color: #66b1ff;
            }
            .titleButton[disabled]{
                border: 1px solid #c0c4cc;
                color: #c0c4cc;
            }
        }
        .content{
            font-size: 16px;
            font-weight: 400;
            color: #333;
            line-height: 32px;
            padding-left:20px;
        }
        .fileShow {
            padding-left:20px;
            display: flex;
            flex-wrap: wrap;
            .fileItem {
                margin-right: 20px;
                margin-bottom: 10px;
                .fileItemMain{
                    padding:15px;
                    width: 360px;
                    height: 80px;
                    display: flex;
                     position: relative;
                    border-radius: 4px;
                    border: 1px solid #DDDDDD;
                    .fileInfo{
                        display: flex;
                        flex-direction: column;
                        flex: 1;
                        padding-left: 14px;
                        height: 50px;
                        .fileTitle {
                            width: 260px;
                            overflow: hidden;
                            white-space: nowrap;
                            text-overflow: ellipsis;
                            line-height: 20px;
                            font-size: 16px;
                            color: #333333;
                        }
                        .fileAction {
                            margin-top: 12px;
                            display: flex;
                            line-height: 16px;
                            .fileSize {
                                font-weight: 400;
                                color: #999999;
                            }
                            .fileButtons {
                                flex: 1;
                                text-align: right;
                                .fileButton {
                                    padding: 0;
                                    font-size: 14px;
                                    line-height: 16px;
                                    img {
                                        margin-right: 5px;
                                    }
                                }
                            }
                        }
                    }
                    .deleteButton {
                        position: absolute;
                        top: 4px;
                        right: 4px;
                        .deleteButtonEl {
                            display: inline-block;
                            width: 16px;
                            height: 16px;
                            line-height: 16px;
                            border-radius: 8px;
                            background: #fff;
                            color: #ccc;
                            text-align: center;
                        }
                        .deleteButtonEl:hover {
                            color: #fff;
                            background: #ccc;
                        }
                    }
                }
            }
        }
    } 
</style>